package com.example.jasonsun.sharelib.platform;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import com.example.jasonsun.sharelib.R;
import com.example.jasonsun.sharelib.config.Cache;
import com.example.jasonsun.sharelib.utils.Util;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.modelmsg.WXWebpageObject;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

/**
 * 微信好友和微信朋友圈
 */
public class WeichatPlatform implements SharePlatform {
    private IWXAPI mApi;
    private Activity mActivity;

    public WeichatPlatform(Activity activity) {
        mActivity = activity;
        mApi = WXAPIFactory.createWXAPI(mActivity, Cache.WECHAT_APP_ID);
    }

    @Override
    public void share(int platform, String title, String content, String imgUrl, String webUrl) {
        if (platform != SharePlatform.WECHAT_CIRCLE && platform != SharePlatform.WECHAT_SESSION) {
            throw new IllegalArgumentException("platform wrong");
        }
        boolean isTimeLine = platform == SharePlatform.WECHAT_CIRCLE;
        doShare(title, content, imgUrl, webUrl, isTimeLine);
    }

    @Override
    public void login() {
        final SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = "wechat_sdk_demo_test";
        mApi.sendReq(req);
    }

    @Override
    public void logout() {
    }

    private void doShare(String title, String content, String imgUrl, String targetUrl, boolean isTimeLine) {
        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = targetUrl;
        WXMediaMessage msg = new WXMediaMessage(webpage);
        msg.title = title;
        msg.description = content;
        Bitmap thumb = BitmapFactory.decodeResource(mActivity.getResources(), R.drawable.ic_qq);
        msg.thumbData = Util.bmpToByteArray(thumb, true);

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("webpage");
        req.message = msg;
        req.scene = isTimeLine ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneSession;
        mApi.sendReq(req);
    }

    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }

}
